package com.scuec.groupfive.controller;

import com.scuec.groupfive.entity.FileUploadEntity;
import com.scuec.groupfive.entity.UserInfo;
import com.scuec.groupfive.service.UserproService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@RestController
@RequestMapping("/userpro")
@CrossOrigin
public class UserproController {
    private static final String UPLOAD_DIR = "D:/uploads/";

    @Autowired
    private UserproService userproService;

    // 新增：根据邮箱查询用户
    // http://localhost:8080/userpro/findByEmail?email=user001@stu.com
    @GetMapping("/findByEmail")
    public ResponseEntity<?> getUserByEmail(@RequestParam String email) {
        try {
            UserInfo userInfo = userproService.getUserByEmail(email);
            if (userInfo == null) {
                return ResponseEntity.status(404).body("未找到该邮箱对应的用户");
            }
            // 清除密码等敏感信息
            userInfo.setPassword(null);
            return ResponseEntity.ok(userInfo);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("查询用户时发生错误: " + e.getMessage());
        }
    }



    // http://localhost:8080/userpro/find?id=1
    @GetMapping("/find")
    public UserInfo getUserById(Integer id) {
        UserInfo userInfo = userproService.getUserInfoById(id);
        return userInfo;
    }

    // http://localhost:8080/userpro/update
    @PutMapping("/update")
    public int updateUserInfo(@RequestBody UserInfo userInfo) {
        int result = userproService.updateUserInfo(userInfo);
        return result;
    }

    // http://localhost:8080/userpro/updateProfile
    @PutMapping("/updateProfile")
    public int updateUserProfile(@RequestBody UserInfo userInfo) {
        // 只更新基本资料信息，不包括敏感信息
        int result = userproService.updateUserProfile(userInfo);
        return result;

    }

    // http://localhost:8080/userpro/updatePassword
    @PutMapping("/updatePassword")
    public int updateUserPassword(@RequestBody UserInfo userInfo) {
        // 专门用于修改密码的接口
        int result = userproService.updateUserPassword(userInfo);
        return result;
    }
    // http://localhost:8080/userpro/uploadAvatar
    // 头像上传接口 (新增)
    @PostMapping("/uploadAvatar")
    public ResponseEntity<FileUploadEntity> uploadAvatar(@RequestParam("file") MultipartFile file) {
        try {
            String uploadDir = "D:/uploads/";

            Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFilename = UUID.randomUUID().toString() + fileExtension;

            Path filePath = uploadPath.resolve(newFilename);
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            FileUploadEntity fileUploadEntity = new FileUploadEntity();
            String avatar = "http://localhost:8080/uploads/" + newFilename;
            fileUploadEntity.setFile(avatar);

            return ResponseEntity.status(200).body(fileUploadEntity);
            //return ResponseEntity.status(200).body(fullUrl);

        } catch (Exception e) {
            FileUploadEntity fileUploadEntity = new FileUploadEntity();
            fileUploadEntity.setFile("头像上传失败: " + e.getMessage());
            return ResponseEntity.status(500).body(fileUploadEntity);
        }
    }
    // http://localhost:8080/userpro/delete?userId=1
    @DeleteMapping("/delete")
    public ResponseEntity<String> deleteUser(@RequestParam Integer userId) {
        try {
            int result = userproService.deleteUserById(userId);

            if (result > 0) {
                return ResponseEntity.ok("用户删除成功");
            } else {
                return ResponseEntity.status(404).body("用户不存在或删除失败");
            }
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("删除用户时发生错误: " + e.getMessage());
        }
    }

}